/*
 @description: 广告交易-设置公众号
 @date: 2015-12-24
 @author: Nero(Nero@Nero-zou.com)
 */
var LoginWXB=window.top.LoginWXB;
var PageUtil=window.top.PageUtil;
var Util=window.top.Util;
var Accounts=window.top.Accounts;
var WechatFetch=window.top.WechatFetch;
//Vue.config.debug = true;


Vue.filter('accountAddedTips', function (type) {
    var map={
        '0':'--',
        '1':'该公众号已经添加过了',
        '2':'该公众号已被添加到别的账号下'
    };
    if(map[type]){
        return map[type];
    }
    return type;
});

Vue.filter('priceType', function (type) {
    var map={
        'price0':'单图文',
        'price1':'多图文①',
        'price2':'多图文②',
        'price3':'多图文③'
    };
    if(map[type]){
        return map[type];
    }
    return type;
});

Vue.filter('numberly', function (number) {
    return ~~number;
});

Vue.filter('priceFriendly', function (number) {
    if(isNaN(number) || number===0){
        return '不接单';
    }
    number= Math.floor(number);
    return ("￥" + number).split('').reverse().join('').replace(/(\d{3})(?=\d)/gim, '$1,').split('').reverse().join('');
});

Vue.filter('numberFriendly', function (number) {
    if(isNaN(number)){
        return number;
    }
    return ("" + number).split('').reverse().join('').replace(/(\d{3})(?=\d)/gim, '$1,').split('').reverse().join('');
});

Vue.filter('totalFansPrice', function (price, fans_num) {
    return (fans_num / 10000 * price).toFixed(2);
});

Vue.filter('adTypeToText', function (types,adTypeMap) {
    if (types instanceof Array === false) {
        return;
    }
    var result = [];
    for (var i = 0; i < types.length; i++) {
        var obj = types[i];
        result.push(adTypeMap[obj] ? adTypeMap[obj].tag_name : '其他');
    }
    return result.join('、');
});

var vm = new Vue({
    el: '#adAccounts',
    data: {
        nowTime:Date.now(),
        wxbUserInfo:{mobile:'',nickname:'',is_verify_mobile:'0'},
        adTypeMap:{},
        phoneNum: '',//用户手机号
        isAllChecked:false,
        adAccounts: [],//已添加公众号 数据
        hasAddedAccounts: {},
        adAccountsPager: {
            page: 1,
            perPage: 10,
            totalNum:0,
            totalPages:0,
            loading:false
        },//分页数据
        status:{
            showAddAccountStep1:false,
            showAddAccountStep2:false,
            showSetMpAdAccount:false,
            showSetMpAdAccountPrice:false,//设置公众号单个位置的价格
            nowPriceType:'price1',//设置公众号单个位置的价格 时的类型
            accountsForEditShowAll:false,//添加接单公众号时，是否显示不可添加的公众号
            showBindMobile:false//是否显示 绑定手机号
        },
        accountsForEdit:[],//可以添加的公众号
        isAddAccoutsAllChecked:false,
        accountsForEditPager:{
            start: 0,
            perPage: 8
        },//添加公众号
        setAccountDetailData:getDetailSetData(),
        bindMobileData:{
            mobile:'',
            code:'',
            code_sending:false,
            saving:false,
            latest_send_time:0
        }
    },
    computed:{
        checkedEditAccounts: function () {
            var result=[];
            for (var i = 0; i < this.accountsForEdit.length; i++) {
                var obj = this.accountsForEdit[i];
                if(obj.checked){
                    result.push(obj);
                }
            }
            return result;
        },
        accountsForEditVisable: function () {
            //可以添加接单的公众号
            var result=[];
            for (var i = 0; i < this.accountsForEdit.length; i++) {
                var obj = this.accountsForEdit[i];
                if(this.status.accountsForEditShowAll){
                    result.push(obj);
                }else{
                    if(obj.addType===0){
                        result.push(obj);
                    }
                }
            }
            return result;
        },
        canSendVoice: {
            cache: false,
            get: function () {
                var latestSendTime=this.bindMobileData.latest_send_time;
                if(latestSendTime!==0 && this.nowTime - latestSendTime>1000*60*3){
                    return true;
                }
                return false;
            }
        }
    },
    watch: {
        setAccountDetailData:{
            deep:true,
            handler:function(newVal,oldVal){
                for (var key in newVal) {
                    if(key.match(/^price/)){
                        var result=parseInt(newVal[key]);
                        if(isNaN(result)){
                            result=0;
                        }
                        newVal[key]=result;
                    }
                }
                return newVal;
            }
        }
    },
    methods: {
        init: function () {
            this.status.showAddAccountStep1=false;
            this.status.showAddAccountStep2=false;
            this.status.showSetMpAdAccount=false;
            this.status.showSetMpAdAccountPrice=false;
            this.adAccountsPager.page=1;
            this.getAdAccounts();
            this.matchLocalMpAccounts();
            this.getWxbUserInfo();
        },
        getWxbUserInfo : function () {
            var _this=this;
            LoginWXB.getWxbUserInfo().then(function (response) {
                _this.$set('wxbUserInfo',response);
            }).catch(function (err) {
                toastr.error(err,"加载微小宝账号信息失败");
            });
        },
        checkWxbUserMobile: function () {
            var _this=this;
            return new Promise(function(resolve,reject){
                var is_verify_mobile=_this.wxbUserInfo.is_verify_mobile;
                if(is_verify_mobile==='1'){
                    resolve();
                }else{
                    _this.showBindMobile();
                    reject();
                }
            });
        },
        showBindMobile: function () {
            var _this=this;
            _this.status.showBindMobile=true;
            _this.bindMobileData.latest_send_time=0;
        },
        bindMobileSend : function (type) {
            var _this=this;
            if(_this.bindMobileData.code_sending){
                return;
            }
            var mobile=_this.bindMobileData.mobile;
            if(Util.isMobile(mobile)){
                _this.bindMobileData.code_sending=true;
                LoginWXB.sendMobileCode(mobile,type).then(function () {
                    _this.bindMobileData.latest_send_time=Date.now();
                    _this.bindMobileData.code_sending=false;
                    toastr.success(type==='text'?"请注意查收手机短信":"请注意接听我们的电话","发送验证码成功");
                }).catch(function (err) {
                    _this.bindMobileData.code_sending=false;
                    toastr.error(err,"发送验证码失败");
                });
            }else{
                toastr.error("","请填写正确的手机号");
            }
        },
        bindMobileSure: function () {
            var _this=this;
            var mobile=_this.bindMobileData.mobile;
            var code=_this.bindMobileData.code;
            if(Util.isMobile(mobile) && code!==''){
                _this.bindMobileData.saving=true;
                LoginWXB.setWxbUserMobile(mobile,code).then(function () {
                    _this.bindMobileData.saving=false;
                    _this.status.showBindMobile=false;
                    _this.wxbUserInfo.is_verify_mobile='1';
                    _this.wxbUserInfo.mobile=mobile;
                    toastr.success("","绑定手机号码成功");
                }).catch(function (err) {
                    _this.bindMobileData.saving=false;
                    toastr.error(err,"绑定手机号码成功");
                });
            }
        },
        bindMobileClose: function () {
            this.status.showBindMobile=false;
        },
        autoSetElsePrice: function () {
            var datailData=this.setAccountDetailData;
            var autoList=['price0_yg','price2_yg','price3_yg','price0_lg','price1_lg','price2_lg','price3_lg'];
            var priceAutoSetPercent={
                'price0_yg':1.3,
                'price2_yg':0.7,
                'price3_yg':0.4,
                'price0_lg':1.3,
                'price1_lg':1,
                'price2_lg':0.7,
                'price3_lg':0.4
            };// [1.3,1,0.7,0.3] 单图：多图①：多图②：多图③

            var initFieldNum=0;//价格为0的字段数
            for (var i = 0; i < autoList.length; i++) {
                var key = autoList[i];
                if(datailData[key]===0){
                    initFieldNum++;
                }
            }
            if(initFieldNum===autoList.length){//说明除了 单图文1 有价格 别的都为零，即满足自动填充规则
                var price1=datailData.price1_yg;
                for (var key2 in priceAutoSetPercent) {
                    if(priceAutoSetPercent.hasOwnProperty(key2)){
                        datailData[key2]=price1*priceAutoSetPercent[key2];
                    }
                }
            }

        },
        checkAll: function () {
            this.isAllChecked=!this.isAllChecked;
            for (var i = 0; i < this.adAccounts.length; i++) {
                var obj = this.adAccounts[i];
                obj.checked=this.isAllChecked;
            }
        },
        updateLocalMpAccountInfo: function (account) {
            if(account.fetching){
                return;
            }
            account.fetching=true;
            var _this=this;
            var accountInfo=window.top.Accounts.getAccountInfo(account.raw_id);
            PageUtil.updateMpAccountInfo(accountInfo).then(function (newAccount) {
                account.fetching=false;
                var newData=transAccount(newAccount);
                for (var key in newData) {
                    if(newData.hasOwnProperty(key)){
                        account[key]=newData[key];
                    }
                }
                toastr.success("","更新公众号数据成功");
            }).catch(function (err) {
                account.fetching=false;
                toastr.error(err,"更新公众号数据出错");
            });
        },
        matchLocalMpAccounts: function () {
            var _this=this;
            var raw_ids=[];
            var accounts=getLocalMpAccounts();
            for (var i = 0; i < accounts.length; i++) {
                var obj = accounts[i];
                raw_ids.push(obj.raw_id);
            }
            LoginWXB.matchLocalMpAccounts(raw_ids).then(function (response) {
                _this.$set('hasAddedAccounts',response.data);
            }).catch(function (e) {
                toastr.error("","获取接单公众号数据失败");
            });
        },
        getAdAccounts: function () {
            var _this=this;
            _this.adAccountsPager.loading=true;
            LoginWXB.getAdMpAccounts(this.adAccountsPager.page).then(function (response) {
                _this.adAccountsPager.loading=false;
                var data=[];
                for (var i = 0; i < response.data.length; i++) {
                    data.push(parseAccountsData(response.data[i]));
                }
                _this.adAccountsPager.totalNum=response.pager.numRecords;
                _this.adAccountsPager.totalPages=response.pager.numPages;

                for (var j = 0; j < response.tag.length; j++) {
                    var obj = response.tag[j];
                    _this.adTypeMap[obj.id]=obj;
                }
                _this.$set('adAccounts',data);
            }).catch(function (e) {
                _this.adAccountsPager.loading=false;
                toastr.error(e,"加载公众号列表失败");
            });

        },
        adAccountsPrev: function () {
            if(this.adAccountsPager.page<=1){
                toastr.error("","已经是第一页了");
                return;
            }
            this.adAccountsPager.page--;
            this.getAdAccounts();
        },
        adAccountsNext: function () {
            if(this.adAccountsPager.page>=this.adAccountsPager.totalPages){
                toastr.error("","已经是最后一页了");
                return;
            }
            this.adAccountsPager.page++;
            this.getAdAccounts();
        },
        addAccountStep1: function () {
            var _this=this;
            this.checkWxbUserMobile().then(function () {
                _this.status.showAddAccountStep1=true;
                _this.$set('accountsForEdit',getCanAddMpAccounts());
            }).catch(function () {

            });

        },
        checkOneAddAccount: function (account) {
            if(account.addType===0){
                account.checked=!account.checked;
            }
        },
        checkAllAddAccouts : function () {
            this.isAddAccoutsAllChecked=!this.isAddAccoutsAllChecked;
            for (var i = this.accountsForEditPager.start; i < this.accountsForEdit.length; i++) {
                if(i-this.accountsForEditPager.start < this.accountsForEditPager.perPage){
                    var obj = this.accountsForEdit[i];
                    if(obj.addType===0){
                        obj.checked=this.isAddAccoutsAllChecked;
                    }
                }
            }
        },
        resetAccAccountsCheck : function () {
            this.isAddAccoutsAllChecked=false;
            for (var i = 0; i < this.accountsForEdit.length; i++) {
                var obj = this.accountsForEdit[i];
                obj.checked=this.isAddAccoutsAllChecked;

            }
        },
        accountsForEditPrev: function () {
            this.resetAccAccountsCheck();
            var result=this.accountsForEditPager.start-this.accountsForEditPager.perPage;
            if(result>=0){
                this.accountsForEditPager.start=result;
            }
        },
        accountsForEditNext: function () {
            this.resetAccAccountsCheck();
            var result=this.accountsForEditPager.start+this.accountsForEditPager.perPage;
            if(result<=this.accountsForEdit.length){
                this.accountsForEditPager.start=result;
            }
        },
        addAccountStep2: function () {
            var ch_accounts=this.checkedEditAccounts;
            if(ch_accounts.length===0){
                toastr.error("请至少选择一个公众号","提示");
                return;
            }
            var data={};
            data.fans_num=ch_accounts[0].fans_num;
            this.setAccountDetailData=getDetailSetData(data);
            this.status.showAddAccountStep1=false;
            this.status.showAddAccountStep2=true;
        },
        detailSetSure: function () {
            var _this=this;
            var data=this.setAccountDetailData;
            var postData={
                weixin_origin_id:[],
                biz:[],
                desc:[],
                weixin_name:[],
                weixin_id:[],
                fans_num:[],
                fans_num_male:[],
                fans_num_female:[],
                is_weixin_verify:[],
                head_image:[],
                qrcode:[]
            };
            if(_this.status.showSetMpAdAccount || _this.status.showSetMpAdAccountPrice){//编辑时
                postData={
                    media_id:[],
                    is_onsale:data.is_onsale
                };
            }

            //这段 新增、编辑 公用
            postData.multi_first_price=data.price1_yg;
            postData.multi_first_price2=data.price1_lg;
            postData.multi_second_price=data.price2_yg;
            postData.multi_second_price2=data.price2_lg;
            postData.multi_other_price=data.price3_yg;
            postData.multi_other_price2=data.price3_lg;
            postData.single_price=data.price0_yg;
            postData.single_price2=data.price0_lg;
            postData.accept=data.accept_tags;
            postData.reject=data.reject_tags;

            if(_this.status.showAddAccountStep2) {//新增时
                for (var i = 0; i < this.checkedEditAccounts.length; i++) {
                    var obj = this.checkedEditAccounts[i];
                    var fansInfo=Accounts.getAccountStat(obj.raw_id).fansInfo;

                    postData.weixin_origin_id.push(obj.raw_id);
                    postData.biz.push(Util.utf8ToBase64(obj.uin));
                    postData.desc.push(obj.desc?obj.desc:'');
                    postData.weixin_name.push(obj.nick_name);
                    postData.weixin_id.push(obj.user_name ? obj.user_name : '');
                    postData.fans_num.push(obj.fans_num ? obj.fans_num : '0');
                    postData.fans_num_male.push(fansInfo.male?fansInfo.male:'0');
                    postData.fans_num_female.push(fansInfo.female?fansInfo.female:'0');
                    postData.head_image.push(obj.avatar || "");//无头像 设置为空
                    postData.qrcode.push(obj.qrcode || "");//无二维码设置为空串
                    postData.is_weixin_verify.push(obj.is_verify || 0);
                }
            }

            if(_this.status.showSetMpAdAccount || _this.status.showSetMpAdAccountPrice){//编辑时
                for (var j = 0; j < this.checkedEditAccounts.length; j++) {
                    postData.media_id.push(this.checkedEditAccounts[j].id);
                }
            }

            _this.setAccountDetailData.saving=true;
            LoginWXB.setAdMpAccounts(postData).then(function () {
                _this.setAccountDetailData.saving=false;
                toastr.success("","保存成功");
                _this.init();
            }).catch(function (e) {
                _this.setAccountDetailData.saving=false;
                toastr.error(e,"保存失败");
            });
        },
        reject_tagsChange: function () {
            var temp={};
            for (var i = 0; i < this.setAccountDetailData.reject_tags.length; i++) {
                temp[this.setAccountDetailData.reject_tags[i]]=true;
            }
            var accept_tags=[];
            for (var j = 0; j < this.setAccountDetailData.accept_tags.length; j++) {
                var id=this.setAccountDetailData.accept_tags[j];
                if(temp[id]===undefined){
                    accept_tags.push(id);
                }
            }
            this.setAccountDetailData.accept_tags=accept_tags;
        },
        accept_tagsChange: function () {
            var temp={};
            for (var i = 0; i < this.setAccountDetailData.accept_tags.length; i++) {
                temp[this.setAccountDetailData.accept_tags[i]]=true;
            }
            var reject_tags=[];
            for (var j = 0; j < this.setAccountDetailData.reject_tags.length; j++) {
                var id=this.setAccountDetailData.reject_tags[j];
                if(temp[id]===undefined){
                    reject_tags.push(id);
                }
            }
            this.setAccountDetailData.reject_tags=reject_tags;
        },
        setMpAdAccount:function(account){
            this.status.showSetMpAdAccount=true;
            var forEditData=_.extend({},account,{checked:true});
            this.$set('accountsForEdit',[forEditData]);
            this.$set('setAccountDetailData',getDetailSetData(forEditData));

        },
        detailSetClose: function () {
            this.status.showAddAccountStep2=false;
            this.status.showSetMpAdAccount=false;
            this.status.showSetMpAdAccountPrice=false;
        },
        detailSetCancel: function () {
            if(this.status.showAddAccountStep2){
                this.status.showAddAccountStep1=true;
                this.status.showAddAccountStep2=false;
            }else{
                this.detailSetClose();
            }

        },
        setMultiAccounts: function () {
            this.status.showSetMpAdAccount=true;
            var forEditData=[];
            for (var i = 0; i < this.adAccounts.length; i++) {
                var account = this.adAccounts[i];
                if(account.checked){
                    forEditData.push(_.extend({},account));
                }
            }
            this.$set('accountsForEdit',forEditData);
            this.$set('setAccountDetailData',getDetailSetData());
        },
        setAccountPrice: function (account,type) {
            this.status.showSetMpAdAccountPrice=true;
            this.status.nowPriceType=type;
            var forEditData=_.extend({},account,{checked:true});
            this.$set('accountsForEdit',[forEditData]);
            this.$set('setAccountDetailData',getDetailSetData(forEditData));
        },
        showPageHelp: function () {
            window.top.openUrlByOuter('http://www.wxb.com/help?id=87');
        },
        show_e_Wwb: function () {
            window.top.openUrlToBrowser('http://e.wxb.com');
        },
        showQQ: function () {
            window.top.openUrlByOuter('http://b.qq.com/webc.htm?new=0&sid=800033932&o=client.wxb.com&q=7',{
                width:644,
                height:500
            });
        },
        updateMpAdAccount: function (account) {
            var _this=this;
            if(account.updating){
                return;
            }
            var accountInfo=Accounts.getAccountInfo(account.raw_id);
            if(!accountInfo.wxid){
                toastr.error("请先添加该公众号到客户端中","更新公众号数据失败");
                return;
            }
            account.updating=true;
            PageUtil.updateMpAccountInfo(accountInfo).then(function (newAccount) {
                var fansInfo=Accounts.getAccountStat(account.raw_id).fansInfo;
                var data={
                    id:[account.id],
                    desc:[newAccount.desc?newAccount.desc:''],
                    wx_name:[newAccount.nickName],
                    wx_alias:[newAccount.userName],
                    biz:[Util.utf8ToBase64(newAccount.uin)],
                    total_fans_num:[newAccount.totalFans],
                    male_fans_num:[fansInfo.male?fansInfo.male:'0'],
                    female_fans_num:[fansInfo.female?fansInfo.female:'0']
                };

                if(!data.total_fans_num){
                    toastr.error("粉丝数据不正常","更新公众号数据失败");
                    return;
                }

                LoginWXB.updateAdMpAccountInfo(data).then(function () {
                    account.updating=false;
                    account.fans_num=newAccount.totalFans;
                    toastr.success("","更新公众号数据成功");
                }).catch(function () {
                    toastr.error("微小宝服务器繁忙","更新公众号数据失败");
                    account.updating=false;
                });
            }).catch(function (err) {
                account.updating=false;
                if(err===404){
                    toastr.error("请先添加该公众号到客户端中","更新公众号数据失败");
                    return;
                }
                toastr.error(err,"更新公众号数据失败");
            });
        }
    }

});

setInterval(function () {
    vm.$set('nowTime',Date.now());
},1000);

/**
 * 转换服务器端数据
 * @param data
 * @returns {*}
 */
function parseAccountsData(data) {
    var result = _.extend({
        checked: false
    }, {
        id: data.id,
        updating: false,
        raw_id: data.weixin_origin_id,
        avatar: data.head_image || '',
        nick_name: data.weixin_name,
        user_name: data.weixin_id,
        fans_num: data.fans_num,
        price0_yg: data.single_price/100,
        price1_yg: data.multi_first_price/100,
        price2_yg: data.multi_second_price/100,
        price3_yg: data.multi_other_price/100,
        price0_lg: data.single_price2/100,
        price1_lg: data.multi_first_price2/100,
        price2_lg: data.multi_second_price2/100,
        price3_lg: data.multi_other_price2/100,
        is_onsale: data.is_onsale,
        accept_tags: data.accept_tags,
        reject_tags: data.reject_tags
    });

    return result;
}



/**
 * 获取本地的公众号
 * @returns {*}
 */
function getLocalMpAccounts(){
    var accounts=window.top.Accounts.getAllAccount();
    var result=[];
    for (var i = 0; i < accounts.length; i++) {
        var obj = accounts[i];
        result.push(transAccount(obj));
    }
    return result;
}

/**
 * 转换本地公众号数据
 * @param obj
 * @returns {{raw_id: *, avatar: *, nick_name: (*|string), user_name: (*|string), fans_num: *}}
 */
function transAccount(obj){
    return {
        raw_id:obj.wxid,
        desc:obj.desc,
        uin:obj.uin,
        avatar:obj.avatar || ('http://open.weixin.qq.com/qr/code/?username='+ obj.wxid),
        qrcode: "http://mp.weixin.qq.com/mp/qrcode?scene=10000005&size=256&__biz="+Util.utf8ToBase64(''+obj.fake_id) ,
        nick_name:obj.nickName,
        user_name:obj.userName,
        fans_num: obj.totalFans,
        male_fans_num: obj.totalMaleFans,
        female_fans_num: obj.totalFemaleFans,
        is_verify:obj.is_wx_verify
    };
}

/**
 * 获取可以添加的公众号
 */
function getCanAddMpAccounts(){
    var accounts=getLocalMpAccounts();
    var result=[];
    var hasAddedAccounts=vm.hasAddedAccounts;
    for (var i = 0; i < accounts.length; i++) {
        var obj = accounts[i];
        var raw_id=obj.raw_id;
        var addType=hasAddedAccounts[raw_id];
        obj.checked=false;
        obj.fetching=false;
        obj.addType=addType;//是否已添加 - 0：未添加过，1：已添加，2：添加在别的公众号名下
        result.push(obj);
    }
    return result;
}

function getDetailSetData(data){
    var defaultData={
        saving:false,
        is_onsale:"1",
        fans_num:0,
        price0_yg:0,//硬广价
        price1_yg:0,
        price2_yg:0,
        price3_yg:0,
        price0_lg:0,//软广价
        price1_lg:0,
        price2_lg:0,
        price3_lg:0,
        accept_tags:[],//想接的广告类型
        reject_tags:[]//不想接的广告类型
    };
    _.extend(defaultData,data);
    return defaultData;
}
